package com.zijin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.zijin.constant.MessageConstant;
import com.zijin.exception.BaseException;
import com.zijin.service.FileUploadService;
import com.zijin.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * @deprecated  FileUploadServiceImpl
 * @author JWei Xu
 */

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Resource
    @Lazy
    private AliOssUtil aliOssUtil;

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            //原始文件名
            final String originalFilename = file.getOriginalFilename();
            if(ObjectUtil.isEmpty(originalFilename)){
                throw new BaseException();
            }
            //截取原始文件名的后缀   dfdfdf.png
            assert originalFilename != null;
            final String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID() + extension;

            //文件的请求路径
            return aliOssUtil.upload(file.getBytes(), objectName);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.toString());
        }
        throw new BaseException(MessageConstant.UPLOAD_FAILED);
    }

    @Override
    public String uploadFile(byte[] bytes, String fileName) {
        try {


            //截取原始文件名的后缀   dfdfdf.png
            String extension = fileName.substring(fileName.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID() + extension;

            //文件的请求路径
            return aliOssUtil.upload(bytes, objectName);
        } catch (Exception e) {
            log.error("文件上传失败：{}", e.toString());
        }
        throw new BaseException(MessageConstant.UPLOAD_FAILED);
    }
}
